<?php
declare (strict_types=1);
/**
 * @Description:
 * @Author: Chern
 * @Date: 2023/7/10
 * @Time: 17:10
 */

namespace app\controller;

use app\BaseController;
use app\message;
use app\model\CluePerson;
use app\model\Operate;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderOtherCertificateBusiness;
use app\model\OrderPersonCertificateRegister;
use app\model\SystemMenu;
use app\model\SystemOperateLog;
use app\model\User;
use app\model\UserOrganization;
use app\service\System;
use app\stateData;
use app\validate\ClueUPersonList;
use app\validate\Organization;
use app\Request;
use think\exception\ValidateException;
use think\facade\Cache;


class SystemOrganizationalStructure extends BaseController
{

    /**
     * 用户架构控制器
     */

    //查询系统现有架构
    public function getOrganizationalStructure(UserOrganization $model, System $system)
    {
        $result = $model->getStructure();

        $result = $system->menuTreeList($result);

        if ($result) {
            return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
        }
        return ReJson(message::$ERROR_CODE, message::$ERR_SELECT_DATA);
    }

    //修改架构名称
    public function updateOrganizationalStructure(Request $request, UserOrganization $model, SystemOperateLog $log)
    {
        $param = $request->post();

        $request = $model->updateStructure($param);

        if ($request) {
            return ReJson(message::$SUCC_CODE, message::$SUCC_UPDATE);
        }
        $log->addOperate($request->param('user_login_id'), message::$ORG_STR, message::$SUCC_SYSTEM_UPDATE_ZZJG);

        return ReJson(message::$ERROR_CODE, message::$ERR_UPDATE);
    }

    //添加架构
    public function insertOrganizationalStructure(Request $request, SystemOperateLog $log, UserOrganization $model)
    {
        $param = $request->post(['title', 'parent_id', 'type']);

        try {

//            Validate(Organization::class)->check($param);

        } catch (ValidateException $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        $result = $model->insertStructure($param);

        if ($result) {

            //添加操作日志
            $log->addOperate($request->param('user_login_id'), message::$ORG_STR, message::$SUCC_SYSTEM_ADD_ZZJG);

            return ReJson(message::$SUCC_CODE, message::$SUCC_SYSTEM_ADD_ZZJG);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_ADD_ZZJG);

    }

    //删除架构
    public function deleteOrganizationalStructure(Request $request, UserOrganization $model, SystemOperateLog $log,User $user)
    {

        $param = $request->post('id');

        try {
            //查看当前组织是否有人员
            $userData = $user->getOrgUserFieldModel($param);
            //查询组织下面是否有组织
            $orgData = $model->getCompanyTypeData($param);
//            Validate(Organization::class)->scene('del')->check($param);

            if($userData || $orgData){
                return ReJson (message::$ERROR_CODE,message::$ERR_PRODUCE_DATA);
            }

        } catch (ValidateException $e) {
            return ReJson(message::$ERROR_CODE, $e->getMessage());
        }

        $result = $model->deleteStructure($param);

        if ($result) {

            //添加操作日志
            $log->addOperate($request->param('user_login_id'), message::$ORG_STR, message::$SUCC_SYSTEM_ADD_ZZJG);

            return ReJson(message::$SUCC_CODE, message::$SUCC_SYSTEM_DEL_ZZJG);
        }

        return ReJson(message::$ERROR_CODE, message::$ERR_SYSTEM_DEL_ZZJG);
    }

    //查询该组织成员列表
    public function getOrgUserList(Request $request, User $user, UserOrganization $userOrganization, System $system)
    {
        $id = $request->get('oid'); //获取组织id

//        if (empty($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $page = $request->get('page') ?: 0;
        $pageNum = $request->get('pageNum') ?: stateData::$_page;
        //获取部门下部门
        $org_list = $userOrganization->getStructure()->toArray();
        if ($id) {
            $org_str = $system->getOrgIdStr($id, $org_list);
            $org_str = rtrim($org_str, ',');
            $org_array = explode(',', $org_str);
        } else {
            $org_array = array_column($org_list, 'id');
        }

        $result = $user->getOrgUserPageListModel($org_array, $pageNum, $page);
        $pages['total'] = $user->getOrgUserCountModel($id);

        $pages['pageNumber'] = $pageNum;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result, $pages);
    }

    //查询该组织成员详情
    public function getOrgUserDetails(Request $request, User $user, UserOrganization $userOrganization, System $system)
    {
        $page = $request->get ('page')?:1;
        $pageNum = $request->get ('pageNum')?:stateData::$_page;
        $id = $request->get('oid'); //获取组织id
        $login_user_id = $request->get('user_login_id');
        $where = [
            'type'=>stateData::$_company_type['user']
        ];

        if ($request->get ('level_id')){
            $where['level_id'] = $request->get ('level_id');
        }

        if ($request->get ('keys') && $request->get ('values')){
            $where = [
                [$request->get ('keys'), 'like', '%'.$request->get ('values').'%'],
            ];
        }

        //获取部门下部门
        $org_list = $userOrganization->getStructure()->toArray();
        if(!$id){
            $user_info = $user->getIdUserData($login_user_id);
            if($user_info['type'] == 1){
                $org_array = array_column($org_list, 'id');
            }else{
                $id = $user_info['department_id']['id'];
                $org_str = $system->getOrgIdStr($id, $org_list);
                $org_str = rtrim($org_str, ',');
                $org_array = explode(',', $org_str);
            }
        }else{
            $org_str = $system->getOrgIdStr($id, $org_list);
            $org_str = rtrim($org_str, ',');
            $org_array = explode(',', $org_str);
        }

//        if ($id) {
//            $org_str = $system->getOrgIdStr($id, $org_list);
//            $org_str = rtrim($org_str, ',');
//            $org_array = explode(',', $org_str);
//        } else {
//            $org_array = array_column($org_list, 'id');
//        }
        $result = $user->getOrgUserListModel($org_array,$where,$page,$pageNum);

        $pages['total'] = $user->getOrgUserCountModel($org_array,$where);
        $pages['pageNum'] = $pageNum;
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result,$pages);
    }

    //数据交接
    public function dataHandover(
        Request                   $request,
        CluePerson                $personModel,
        \app\model\ClueEnterprise $enterpriseModel,
        OrderPersonCertificateRegister $OrderPersonCertificateRegisterModel,
        OrderEnterpriseCertificateRegister $OrderEnterpriseCertificateRegisterModel,
        OrderOtherCertificateBusiness $OrderOtherCertificateBusinessModel,
        OrderEnterpriseCertificateBusiness $OrderEnterpriseCertificateBusinessModel,
        OrderEnterpriseCompany $OrderEnterpriseCompanyModel,
        OrderEnterpriseExchange $OrderEnterpriseExchangeModel
    ){
        $param = $request->post ();

        $validate = new \app\validate\User();
        if (!$validate->scene ('dataHandOver')->check($param)) {
            return ReJson(message::$ERROR_CODE, $validate->getError(), []);
        }

        //分割交接范围
        $handover_data = explode (',',$param['handover_data']);

        foreach ($handover_data as $handover_datum) {
            //交接线索库信息
            if ($handover_datum == 1){
                //交接人才
                $idArr = $personModel->getFUidDataModel($param['push_uid']);
                if ($idArr){
                    $personModel->editHandOverFUidModel($idArr,$param['get_uid']);
                }
            }

            if ($handover_datum == 2){
                //交接注册企业
                $enterIdArr = $enterpriseModel->getFUidDataModel($param['push_uid']);
                if ($enterIdArr){
                    $enterpriseModel->editHandOverFUidModel($enterIdArr,$param['get_uid']);
                }
            }

            if ($handover_datum == 3){
                //交接合作伙伴
                $enterIdArr = $enterpriseModel->getFUidDataModel($param['push_uid'],2);
                if ($enterIdArr){
                    $enterpriseModel->editHandOverFUidModel($enterIdArr,$param['get_uid']);
                }
            }

            if ($handover_datum == 4){
                //交接证书审核
                //查询审核人是转出人的信息
                $personIdArr = $OrderPersonCertificateRegisterModel->getResponsibilityUidDataModel($param['push_uid']);
                if ($personIdArr){
                    $OrderPersonCertificateRegisterModel->editResponsibilityUidDataModel($personIdArr,$param['get_uid']);
                }
                //查询收证人员是转出人的信息
                $getIdArr = $OrderPersonCertificateRegisterModel->getGetUidDataModel($param['push_uid']);
                if ($getIdArr){
                    $OrderPersonCertificateRegisterModel->editGetUidDataModel($getIdArr,$param['get_uid'],$param['get_org']);
                }
                //查询发起人是转出人的信息
                $subIdArr = $OrderPersonCertificateRegisterModel->getSubmitUidDataModel($param['push_uid']);
                if ($subIdArr){
                    $OrderPersonCertificateRegisterModel->editSubmitUidDataModel($subIdArr,$param['get_uid']);
                }
            }

            if ($handover_datum == 5){
                //交接证书证书需求
                //交接销售人员信息
                $enterSaleIdArr = $OrderEnterpriseCertificateRegisterModel->getSaleUidDataModel($param['push_uid']);
                if ($enterSaleIdArr){
                    $OrderEnterpriseCertificateRegisterModel->editSaleUidDataModel($enterSaleIdArr,$param['get_uid'],$param['get_org']);
                }
                //交接收证人员信息
                $enterGetIdArr = $OrderEnterpriseCertificateRegisterModel->getGetUidDataModel($param['push_uid']);
                if ($enterGetIdArr){
                    $OrderEnterpriseCertificateRegisterModel->editGetUidDataModel($enterGetIdArr,$param['get_uid'],$param['get_org']);
                }
                //交接通知人员信息
                $NoticeIdArr = $OrderEnterpriseCertificateRegisterModel->getNoticeIdDataModel($param['push_uid']);
                if ($NoticeIdArr){
                    $OrderEnterpriseCertificateRegisterModel->editNoticeIdDataModel($NoticeIdArr,$param['get_uid']);
                }
            }

            if ($handover_datum == 6){
                //交接证书注册公司证书

                $companyResponsibilityIdArr = $OrderEnterpriseCompanyModel->getResponsibilityUidDataModel($param['push_uid']);
                if ($companyResponsibilityIdArr){
                    $OrderEnterpriseCompanyModel->editResponsibilityUidDataModel($companyResponsibilityIdArr,$param['get_uid']);
                }

                $companyGetIdArr = $OrderEnterpriseCompanyModel->getGetUidDataModel($param['push_uid']);
                if ($companyGetIdArr){
                    $OrderEnterpriseCompanyModel->editGetUidDataModel($companyGetIdArr,$param['get_uid'],$param['get_org']);
                }

                $companySubmitIdArr = $OrderEnterpriseCompanyModel->getSubmitUidDataModel($param['push_uid']);
                if ($companySubmitIdArr){
                    $OrderEnterpriseCompanyModel->editSubmitUidDataModel($companySubmitIdArr,$param['get_uid']);
                }
            }

            if ($handover_datum == 7){
                //交接证书注册倒证
                $exchangeNoticeIdArr = $OrderEnterpriseExchangeModel->getNoticeIdDataModel($param['push_uid']);
                if ($exchangeNoticeIdArr){
                    $OrderEnterpriseExchangeModel->editNoticeIdDataModel($exchangeNoticeIdArr,$param['get_uid']);
                }

                $exchangeGetIdArr = $OrderEnterpriseExchangeModel->getGetUidDataModel($param['push_uid']);
                if ($exchangeGetIdArr){
                    $OrderEnterpriseExchangeModel->editGetUidDataModel($exchangeGetIdArr,$param['get_uid'],$param['get_org']);
                }

                $exchangeSubmitIdArr = $OrderEnterpriseExchangeModel->getSubmitUidDataModel($param['push_uid']);
                if ($exchangeSubmitIdArr){
                    $OrderEnterpriseExchangeModel->editSubmitUidDataModel($exchangeSubmitIdArr,$param['get_uid']);
                }

                $exchangeOutIdArr = $OrderEnterpriseExchangeModel->getOutUidDataModel($param['push_uid']);
                if ($exchangeOutIdArr){
                    $OrderEnterpriseExchangeModel->editOutUidDataModel($exchangeOutIdArr,$param['get_uid'],$param['get_org']);
                }
            }

            if ($handover_datum == 8){
                //交接企业证书
                $businessResponsibilityIdArr = $OrderEnterpriseCertificateBusinessModel->getResponsibilityUidDataModel($param['push_uid']);
                if ($businessResponsibilityIdArr){
                    $OrderEnterpriseCertificateBusinessModel->editResponsibilityUidDataModel($businessResponsibilityIdArr,$param['get_uid']);
                }

                $businessGetIdArr = $OrderEnterpriseCertificateBusinessModel->getGetUidDataModel($param['push_uid']);
                if ($businessGetIdArr){
                    $OrderEnterpriseCertificateBusinessModel->editGetUidDataModel($businessGetIdArr,$param['get_uid'],$param['get_org']);
                }

                $businessSubmitIdArr = $OrderEnterpriseCertificateBusinessModel->getSubmitUidDataModel($param['push_uid']);
                if ($businessSubmitIdArr){
                    $OrderEnterpriseCertificateBusinessModel->editSubmitUidDataModel($businessSubmitIdArr,$param['get_uid']);
                }

                $businessOutIdArr = $OrderEnterpriseCertificateBusinessModel->getOutUidDataModel($param['push_uid']);
                if ($businessOutIdArr){
                    $OrderEnterpriseCertificateBusinessModel->editOutUidDataModel($businessOutIdArr,$param['get_uid'],$param['get_org']);
                }
            }

            if ($handover_datum == 9){
                //交接证书办理
                $otherRespondIdArr = $OrderOtherCertificateBusinessModel->getResponsibilityUidDataModel($param['push_uid']);
                if ($otherRespondIdArr){
                    $OrderOtherCertificateBusinessModel->editResponsibilityUidDataModel($otherRespondIdArr,$param['get_uid']);
                }
                $otherGetIdArr = $OrderOtherCertificateBusinessModel->getGetUidDataModel($param['push_uid']);
                if ($otherGetIdArr){
                    $OrderOtherCertificateBusinessModel->editGetUidDataModel($otherGetIdArr,$param['get_uid'],$param['get_org']);
                }
                $otherSubmitIdArr = $OrderOtherCertificateBusinessModel->getSubmitUidDataModel($param['push_uid']);
                if ($otherSubmitIdArr){
                    $OrderOtherCertificateBusinessModel->editSubmitUidDataModel($otherSubmitIdArr,$param['get_uid']);
                }
            }
        }


        return ReJson (message::$SUCC_CODE,message::$DATA_HAND_OVER_SUCC);
    }


//    //获取数据交接下拉框
    public function getUidDataSelect(
        Request                   $request,
        SystemMenu                $menuModel,
        \app\model\ClueEnterprise $enterpriseModel,
        CluePerson $personModel,
        OrderPersonCertificateRegister $OrderPersonCertificateRegisterModel,
        OrderEnterpriseCertificateRegister $OrderEnterpriseCertificateRegisterModel
    ){
//        $uid = $request->get ('uid');
//
//        if(empty($uid)){
//            return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
//        }
//
//        //查询线索库&订单管理下级菜单
////        $xskId = 37;
////        $ddglId = 44;
////        $hhzId = 91;//回收站
////        $zcqykId = 54;   //注册企业库
////        $hzhbkId = 99; //合作伙伴库
////        $rckId = 52;//人才库
////        $zsshId = 64;//证书审核
////        $zsblId = 65;//证书办理
////        $zszcId = 66; //证书注册
////        $qyzsId = 67;//企业证书
////        $xskMenu = $menuModel->getAliasIdSonDataModel($xskId);
////        $ddglMenu = $menuModel->getAliasIdSonDataModel($ddglId);
////
////        $menuData = array_merge ($xskMenu,$ddglMenu);
//
        $menuData = [
            ['id'=>1,'title'=>'人才库'],
            ['id'=>2,'title'=>'注册企业库'],
            ['id'=>3,'title'=>'合作伙伴库'],
            ['id'=>4,'title'=>'证书审核'],
            ['id'=>'','title'=>'证书注册','childs'=>[['id'=>5,'title'=>'公司需求'],['id'=>6,'title'=>'公司证书'],[ 'id'=>7,'title'=>'倒证']]],
            ['id'=>8,'title'=>'企业证书'],
            ['id'=>9,'title'=>'证书办理'],
        ];
////print_r ($menuData);die;
//        foreach ($menuData as $key=> &$menuDatum) {
//            //查询归属uid信息
//            //注册企业库
//            if ($menuDatum['id'] === 2){
//                $menuDatum['childs'] = $enterpriseModel->getFUidFieldDataModel($uid);
//                continue;
//            }
//            //合作伙伴库
//            if ($menuDatum['id'] === 3){
//                $menuDatum['childs'] = $enterpriseModel->getFUidFieldDataModel($uid,2);
//                continue;
//            }
//            //人才库
//            if ($menuDatum['id'] === 1){
//                $menuDatum['childs'] = $personModel->getFUidFieldDataModel($uid);
//                continue;
//            }
//            //证书审核
//            if ($menuDatum['id'] == 4){
//                $menuDatum['childs'] = $OrderPersonCertificateRegisterModel->getFUidFieldDataModel($uid);
//                continue;
//            }
//            //公司需求
//            if ($menuDatum['id'] == 5){
//                $menuDatum['childs'] = $OrderEnterpriseCertificateRegisterModel->getFUidFieldDataModel($uid);
//                continue;
//            }
//
//        }
//print_r ($menuData);die;
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$menuData);
    }
//    //数据交接
//    public function dataHandover()
//    {
//
//    }
}